<!-- pages/address/add.vue -->
<template>
  <view class="container">
    <!-- 顶部导航 -->
    <view class="nav">
      <view class="back" @click="goBack">
        <image src="/images/icons/back.png" mode="aspectFit"></image>
      </view>
      <view class="title">新增收货地址</view>
      <view class="placeholder"></view>
    </view>

    <!-- 表单区域 -->
    <view class="form-container">
      <!-- 收货人信息 -->
      <view class="form-item">
        <view class="label">收货人</view>
        <input class="input" v-model="form.name" placeholder="请填写收货人姓名" />
        <view class="icon-contact" @click="chooseContact"></view>
      </view>

      <!-- 手机号 -->
      <view class="form-item">
        <view class="label">手机号</view>
        <picker class="country-picker" :value="countryIndex" :range="countryCodes" @change="countryChange">
          <view class="picker-content">{{ countryCodes[countryIndex] }}</view>
        </picker>
        <input class="input phone-input" v-model="form.phone" type="number" placeholder="请填写收货人手机号" maxlength="11" />
      </view>

      <!-- 地址选择 -->
      <view class="address-section">
        <view class="section-header">
          <text class="section-title active">地图选址</text>
          <text class="section-title">地区选址</text>
          <text class="section-subtitle">(含港澳台及海外)</text>
        </view>

        <!-- 当前定位 -->
        <view class="location-box" v-if="locationData">
          <view class="location-info">
            <text>当前定位: {{ locationData.address }}</text>
            <text class="district">{{ locationData.district }}</text>
          </view>
          <button class="use-location" size="mini" @click="useCurrentLocation">使用</button>
        </view>

        <!-- 地址输入 -->
        <view class="address-input-box">
          <view class="label">地址</view>
          <input class="input address-input" v-model="form.detailAddress" placeholder="选择收货地址" disabled />
        </view>

        <!-- 门牌号 -->
        <view class="form-item">
          <view class="label">门牌号</view>
          <input class="input" v-model="form.houseNumber" placeholder="例: 6栋201室" />
        </view>

        <!-- 地址粘贴板 -->
        <view class="paste-address" @click="pasteFromClipboard">
          <text>地址粘贴板</text>
          <image class="arrow-icon" src="/images/icons/arrow-right.png" mode="aspectFit"></image>
        </view>
      </view>

      <!-- 默认地址设置 -->
      <view class="default-section">
        <view class="default-title">设为默认地址</view>
        <view class="default-desc">提醒: 下单时会优先使用该地址</view>
        <switch class="default-switch" color="#ff4d4f" v-model="form.isDefault" />
      </view>

      <!-- 标签选择 -->
      <view class="tags-section">
        <view class="tags-title">标签</view>
        <view class="tags-container">
          <view class="tag-item" v-for="(tag, index) in defaultTags" :key="index" @click="selectTag(tag)">
            {{ tag.name }}
          </view>
          <view class="tag-item custom" @click="showCustomTagInput">
            自定义
          </view>
          <input v-if="showCustomInput" class="custom-input" v-model="customTagName" placeholder="请输入自定义标签" />
        </view>
      </view>
    </view>

    <!-- 底部按钮 -->
    <view class="footer">
      <button class="submit-btn" @click="submitForm">确认</button>
    </view>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import { getLocation, chooseContact, pasteFromClipboard } from '@/utils'

export default {
  data() {
    return {
      form: {
        name: '',
        phone: '',
        country: '+86',
        detailAddress: '',
        houseNumber: '',
        isDefault: false,
        tags: []
      },
      countryCodes: ['+86', '+852', '+853', '+886'], // 示例国际区号
      countryIndex: 0,
      locationData: null,
      defaultTags: [
        { id: 1, name: '学校' },
        { id: 2, name: '家' },
        { id: 3, name: '公司' }
      ],
      showCustomInput: false,
      customTagName: ''
    }
  },
  onLoad(options) {
    // 如果是编辑地址，可在此处获取地址数据
    // const addressId = options.id
    // if (addressId) {
    //   this.getAddressDetail(addressId)
    // }
  },
  methods: {
    goBack() {
      uni.navigateBack()
    },
    // 选择联系人
    chooseContact() {
      chooseContact().then(res => {
        if (res) {
          this.form.name = res.name
          this.form.phone = res.phone
        }
      })
    },
    // 国家码选择
    countryChange(e) {
      this.countryIndex = e.detail.value
      this.form.country = this.countryCodes[this.countryIndex]
    },
    // 获取当前定位
    async getLocationData() {
      try {
        const { status } = await uni.authorize({ scope: 'scope.userLocation' })
        if (status === 'granted') {
          const res = await getLocation()
          if (res) {
            this.locationData = {
              address: res.address,
              district: `${res.province} ${res.city} ${res.district}`
            }
          }
        } else {
          uni.showToast({ title: '需要位置权限', icon: 'none' })
        }
      } catch (error) {
        console.error('获取定位失败:', error)
      }
    },
    // 使用当前定位
    useCurrentLocation() {
      this.form.detailAddress = this.locationData.address
      uni.showToast({ title: '已使用当前定位', icon: 'success' })
    },
    // 粘贴板功能
    async pasteFromClipboard() {
      const text = await pasteFromClipboard()
      if (text) {
        this.form.detailAddress = text
      }
    },
    // 显示自定义标签输入
    showCustomTagInput() {
      this.showCustomInput = true
      setTimeout(() => {
        uni.nextTick(() => {
          const input = this.$el.querySelector('.custom-input')
          if (input) input.focus()
        })
      }, 100)
    },
    // 提交表单
    submitForm() {
      // 表单验证
      if (!this.form.name) {
        return uni.showToast({ title: '请填写收货人姓名', icon: 'none' })
      }
      if (!this.form.phone || !/^1\d{10}$/.test(this.form.phone)) {
        return uni.showToast({ title: '请填写正确的手机号', icon: 'none' })
      }
      if (!this.form.detailAddress) {
        return uni.showToast({ title: '请选择或填写详细地址', icon: 'none' })
      }
      if (!this.form.houseNumber) {
        return uni.showToast({ title: '请填写门牌号', icon: 'none' })
      }

      // 添加标签
      if (this.customTagName) {
        this.form.tags.push(this.customTagName)
        this.customTagName = ''
        this.showCustomInput = false
      }

      // 保存地址数据
      const addressData = { ...this.form, tags: this.form.tags.join(',') }
      console.log('提交地址数据:', addressData)
      
      // 调用API保存地址
      // this.saveAddress(addressData).then(() => {
      //   uni.navigateBack()
      // })

      uni.showToast({ title: '保存成功', icon: 'success' })
      setTimeout(() => {
        uni.navigateBack()
      }, 1000)
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding-bottom: 120rpx;
}

.nav {
  position: sticky;
  top: 0;
  display: flex;
  align-items: center;
  height: 88rpx;
  background: #fff;
  z-index: 100;
  padding: 0 30rpx;

  .back {
    width: 48rpx;
    height: 48rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    image {
      width: 24rpx;
      height: 24rpx;
    }
  }

  .title {
    flex: 1;
    text-align: center;
    font-size: 34rpx;
    font-weight: 500;
  }

  .placeholder {
    width: 48rpx;
  }
}

.form-container {
  background: #fff;
  border-radius: 20rpx 20rpx 0 0;
  margin-top: -20rpx;
  padding: 30rpx;
}

.form-item {
  display: flex;
  align-items: center;
  padding: 24rpx 0;
  border-bottom: 1rpx solid #eee;

  .label {
    width: 120rpx;
    font-size: 30rpx;
    color: #333;
  }

  .input {
    flex: 1;
    height: 40rpx;
    font-size: 28rpx;
  }

  .phone-input {
    width: 60%;
  }

  .country-picker {
    width: 180rpx;
    margin-right: 10rpx;

    .picker-content {
      font-size: 28rpx;
    }
  }

  .icon-contact {
    width: 40rpx;
    height: 40rpx;
    background: #f5f5f5;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.address-section {
  margin-top: 20rpx;

  .section-header {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;

    .section-title {
      padding: 0 20rpx;
      height: 60rpx;
      line-height: 60rpx;
      font-size: 28rpx;
      position: relative;

      &.active {
        color: #333;
        font-weight: 500;

        &::after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 20rpx;
          right: 20rpx;
          height: 4rpx;
          background: #ff4d4f;
          border-radius: 2rpx;
        }
      }
    }

    .section-subtitle {
      font-size: 24rpx;
      color: #999;
      margin-left: 20rpx;
    }
  }

  .location-box {
    background: #f8f8f8;
    border-radius: 10rpx;
    padding: 20rpx;
    margin-bottom: 20rpx;

    .location-info {
      font-size: 28rpx;
      color: #666;
      margin-bottom: 10rpx;
      display: flex;
      justify-content: space-between;

      .district {
        color: #999;
      }
    }

    .use-location {
      background: #fff;
      color: #333;
      font-size: 26rpx;
      border: none;
      padding: 0 20rpx;
      height: 60rpx;
      line-height: 60rpx;
      border-radius: 30rpx;
    }
  }

  .address-input-box {
    margin-bottom: 20rpx;
  }

  .paste-address {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 28rpx;
    color: #666;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #eee;

    .arrow-icon {
      width: 30rpx;
      height: 30rpx;
    }
  }
}

.default-section {
  display: flex;
  align-items: center;
  margin-top: 30rpx;
  padding: 20rpx 0;

  .default-title {
    font-size: 28rpx;
    color: #333;
    margin-right: 10rpx;
  }

  .default-desc {
    font-size: 24rpx;
    color: #999;
    flex: 1;
  }

  .default-switch {
    transform: scale(0.8);
  }
}

.tags-section {
  margin-top: 30rpx;

  .tags-title {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 20rpx;
  }

  .tags-container {
    display: flex;
    flex-wrap: wrap;

    .tag-item {
      padding: 10rpx 20rpx;
      background: #f5f5f5;
      border-radius: 30rpx;
      margin-right: 20rpx;
      margin-bottom: 20rpx;
      font-size: 26rpx;
      color: #333;

      &.custom {
        background: #fff;
        border: 1rpx solid #ddd;
        color: #666;
      }
    }

    .custom-input {
      width: 200rpx;
      height: 60rpx;
      background: #f5f5f5;
      border-radius: 30rpx;
      padding: 0 20rpx;
      font-size: 26rpx;
      margin-top: 10rpx;
    }
  }
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

  .submit-btn {
    width: 90%;
    height: 80rpx;
    line-height: 80rpx;
    background: #ff4d4f;
    color: #fff;
    font-size: 32rpx;
    border-radius: 40rpx;
  }
}
</style>